<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>取消请求</title>
    <script src="https://cdn.bootcdn.net/ajax/libs/axios/0.27.2/axios.min.js"></script>
</head>
<body>
    <button>发送请求</button>
    <button>取消请求</button>

    <script>
        let btns = document.querySelectorAll('button')
        let cancelFun// 用于保存取消请求函数
        //发送请求
        btns[0].onclick = async function(){
           try {
            let response = await axios({
               url:'http://localhost:8000/delay-server',
               method:'get',
               // 配置cancelToken
               cancelToken:new axios.CancelToken((cancel)=>{//cancel: 内部传入的取消请求的函数
                   // 保存cancel函数
                   cancelFun = cancel
               })
            })
            console.log(response.data)
           } catch (error) {
               if(axios.isCancel(error)){  //取消请求类型的错误
                   alert('请求取消')
               }
           }
        }

        //取消请求
        btns[1].onclick = function(){
            if(cancelFun){
                //调用取消请求的函数
                cancelFun()
            }
        }
    </script>
</body>
</html>